import sqlite3
import socket
import json,time,threading
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '../../')))
import backend.DID.DID_interface as did_interface
import backend.P2P.node_find as node_find
import sqlite3
import subprocess,re


 #发送申请函数
def SendApply(id,name):
        friend_list=node_find.Get_friendlist()
        print(f"compelist:{friend_list}")
        with sqlite3.connect("p2p.db", check_same_thread=False,timeout=10) as connect:
            cursor=connect.cursor()
            cursor.execute("SELECT 1 FROM friends WHERE id=?", (id, ))#select 1 是查询是否有符合条件的项
            if cursor.fetchone():
                print("已经是好友，不能重复发送")
                # connect.close()
                return 0
            cursor.execute("SELECT 1 FROM friend_requests WHERE status='pending_send' and receiver_id=?", (id,))
            if cursor.fetchone():
                print("已经发送过好友申请")
                
                #！！！！！！！！！！！！
                #是否更新重发表里的数据
                #如果要更新是在节点发现更新还是在这里更新            
                # connect.close()
                return 0
            cursor.execute("SELECT 1 FROM friend_requests WHERE sender_id=? and status='pending_accept'", (id,))
            #如果对方给你发了，就直接诶同意
            if cursor.fetchone():
                print("对方已发来好友请求，请直接同意")
                return 0
            threading.Thread(target=HandleSendApply, args=(id, name,cursor,connect)).start()
            return 1
def HandleSendApply (id,name,cursor,connect):
        #通过用户名从发现节点中寻找
        friend_list=node_find.Get_friendlist()
        print(friend_list)
        print(id)
        if id in friend_list:
            receiver_ip = friend_list[id]["ip"]
            timestamp = friend_list[id]["timestamp"]
        else:
            print("不存在")
            return 0          
        # with sqlite3.connect("p2p.db", check_same_thread=False,timeout=10) as connect:
        # cursor=connect.cursor()
            # 如果已是好友或已有待处理申请，则跳过
        cursor.execute("SELECT * FROM current_user")
        user=cursor.fetchone()
        userid=user[0]
        sender_ip=user[2]
        timestamp_now = int(time.time() * 1000)
        data={
                "type":"friendrequest",
                "sender_id":userid,
                "sender_name":user[1],
                "sender_ip":sender_ip,
                "timestamp":timestamp_now
            }
        print(data)
        try:
                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                    s.settimeout(10)
                    s.connect((receiver_ip,1236))
                    s.sendall(json.dumps(data).encode())
                    print(data)
                    print("已经成功发送申请!")
                    return 1
        except Exception as e:
                print("目标不在线,存入数据库")
                print(data)
                cursor.execute(
                    '''INSERT INTO friend_requests(sender_id, sender_name, sender_ip, sender_timestamp,
                receiver_id, receiver_name, receiver_ip, receiver_timestamp,
                status, owner) VALUES (?,?, ?, ?,?,?,?,?,?,?)''',
                    (userid,user[1],sender_ip,timestamp_now,id,name,receiver_ip,timestamp,'pending_apply',userid))
        connect.commit()
                # connect.close() 
        return 1   
    #对方同意函数
def Agreement(id,name):
    print("同意")
    threading.Thread(target=HandleAgreement, args=(id, name)).start()
    return 1
def HandleAgreement (id,name):
        
        #通过用户名从发现节点中寻找
        with sqlite3.connect("p2p.db", check_same_thread=False,timeout=10) as conn:
            cursor = conn.cursor()
            cursor.execute("select id from current_user")
            current_id=cursor.fetchone()[0]
            print(current_id)
            print(id)
            cursor.execute("select * from friend_requests")
            rows=cursor.fetchall()
            # print(rows)
            cursor.execute("select sender_name,sender_ip,sender_timestamp from friend_requests where owner=? and status='pending_accept' and sender_id=?"
                        ,(current_id,id))
            row=cursor.fetchone()
            if row:
                message={
                    "sender_id":id,
                    "sender_name":row[0],
                    "sender_ip":row[1],
                    "timestamp":row[2]
                }
                cursor.execute("insert into friends values(?,?,?,?,?,?,?)",(id,row[0],row[1],0,0,row[2],current_id))
                conn.commit()
            else:
                print("不存在")
                return     
            cursor.execute("SELECT * FROM current_user")
            user=cursor.fetchone()
            userid=user[0]
            name=user[1]
            sender_ip=user[2]
            timestamp_m = int(time.time() * 1000)
            data1={
                "type":"friendaccept",
                "sender_id":userid,
                "sender_name":name,
                "sender_ip":sender_ip,
                "timestamp":timestamp_m        }

            try:
                print(f"message的内容为：{message}")
                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                    s.settimeout(10)
                    s.connect((message["sender_ip"], 1236))
                    s.sendall(json.dumps(data1).encode()) 
                    print("已成功发送同意！")
            except Exception as e:
                print(f"对方不在线{e}")
                cursor.execute(
                            '''INSERT INTO friend_requests(sender_id, sender_name, sender_ip, sender_timestamp,
            receiver_id, receiver_name, receiver_ip, receiver_timestamp,
            status, owner) VALUES (?,?, ?, ?,?,?,?,?,?,?)''',
            (userid,name,sender_ip,timestamp_m,message["sender_id"],message["sender_name"],message["sender_ip"],message["timestamp"],'pending_agreement',userid))
                conn.commit()  
            #cursor.execute("DELETE FROM pending_agreement WHERE sender_id=?", (message["sender_id"],))
            cursor.execute("SELECT 1 FROM friends WHERE id = ? AND owner = ?", (id, current_id))
            if cursor.fetchone() is None:
                cursor.execute("INSERT INTO friends VALUES (?, ?, ?, ?, ?, ?, ?)", (id, row[0], row[1], 0, 0, row[2], current_id))
            else:
                print(f"[好友添加] 好友 {id}（当前用户 {current_id}）已存在于 friends 表中，跳过插入")
            cursor.execute("insert into friends(id,name,ip,online,timestamp) values(?,?,?,?,?)",
                        (message["sender_id"],message["sender_name"],message["sender_ip"],0,message["timestamp"]))
            try:
                print("准备删除 friend_requests 中的记录...")
                # cursor.execute("delete from friend_requests where status='pending_accept' sender_id=?",(message["sender_id"],))
                cursor.execute("DELETE FROM friend_requests WHERE status='pending_accept' AND sender_id=?", (message["sender_id"],))
                print("已经从数据库里删除")
            except Exception as e:
                print(f"未在数据库中，无需删除,{e}")
            #cursor.execute("UPDATE pending_friends SET aggrement=? WHERE userid=? AND sender_ip=?", (1, sendid, ip))
            conn.commit()
            print(f"已成功添加{message['sender_name']}")
            # conn.close()
            return 1
#可以和节点发现的监听写在一起    
# 主函数调用时    
def bind(socketio):
        print("bind")
        try:
            with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                s.bind(('0.0.0.0',1236))
                s.bind(('0.0.0.0',1236))
                s.listen()
                print("开始监听...")
                while True:
                    connect,addr = s.accept()
                    print(f"连接到{addr}")
                    data=connect.recv(1024)
                    if not data:
                        print("收到空数据")
                        continue
                    print("收到原始数据：", data)
                    message=json.loads(data.decode())
                    message_thread=threading.Thread(target=handle_message,args=(message,socketio))
                    message_thread.start()
        except Exception as e:
            print("没有接收到消息")

def handle_message(message,socketio):
        with sqlite3.connect("p2p.db", check_same_thread=False,timeout=10) as conn:
            cursor=conn.cursor()
            cursor.execute("SELECT * FROM current_user")
            user= cursor.fetchone()
            userid=user[0]
            cursor.execute("SELECT sender_id FROM friend_requests WHERE status='pending_apply' AND owner=?", (userid,))
            sender_id=cursor.fetchone()
            timestamp_now=int(time.time() * 1000)
            if sender_id is not None:
                sender_id = sender_id[0]
            else:
                print("sender_id 查询结果为 None")
            if message["type"]=="friendrequest":
            #self.Agreement(message)
                print(userid)
                print(sender_id)
                print(message["sender_id"])
                if message["sender_id"]==userid:
                        print(message["sender_id"])
                        print(userid)
                        print("收到自己发的 friendrequest，忽略")
                        # conn.close()
                        return 0
                cursor.execute("""
                    SELECT 1 FROM friend_requests 
                    WHERE sender_id=? AND receiver_id=? AND owner=? AND status='pending_accept'
                """, (message["sender_id"], userid, userid))
                existing = cursor.fetchone()
                if existing:
                    print("已经接收过该 sender_id 发来的好友申请")
                    return
                # 把整个 message 存入 JSON 字段
                cursor.execute("""
                    INSERT INTO friend_requests(sender_id, sender_name, sender_ip,sender_timestamp,receiver_id,receiver_name,receiver_ip,receiver_timestamp,status,owner)
                    VALUES (?, ?, ?, ?, ?, ?,?,?,?,?) 
                """, (
                    message["sender_id"],
                    message["sender_name"],
                    message["sender_ip"],
                    message["timestamp"],
                    userid,
                    user[1],
                    user[2],
                    timestamp_now,
                    "pending_accept",
                    userid
                ))
                conn.commit()
                print("收到好友请求，已存入数据库，等待用户确认")
                #收到好友申请
                #需要向前端发送请求，出现好友同意
                cursor.execute("select sender_id,sender_name from friend_requests where owner=? and status='pending_accept'",(userid,))
                rows=cursor.fetchall()
                data = {
                    "action": "loadAccept",
                    "data": {row[0]: {"name": row[1]} for row in rows}
                }
    
                socketio.emit("client",data)
                print(f"数据：{data}")
            elif message["type"]=="friendaccept":
                if message["sender_id"]==userid:
                        print(message["sender_id"])
                        print(userid)
                        print(message)
                        print("收到自己发的 friendaccept，忽略")
                        # conn.close()
                        return 0
                print(f"同意")
                cursor.execute("INSERT INTO friends(id,name, ip,timestamp,online,host_id,owner) VALUES (?, ?, ?,?,?,?,?)",
                            (message["sender_id"], message["sender_name"], message["sender_ip"],message["timestamp"],0,0,userid))
                conn.commit()
                print(f"{message['sender_name']} 同意了你的好友申请")
                # try:
                #     cursor.execute("delete from pending_friends where id=?",(message["sender_id"],))
                # except Exception as e:
                #     print(f"未在数据库中，不需删除{e}")
                #被拉入群聊,创建群聊时群成员的同步
                # conn.close()
    #后面看看能否写成一个
def retry_requests():
        while True:
            #print("重发申请中...")
            timestamp_now = int(time.time() * 1000)
            connect=sqlite3.connect("p2p.db",check_same_thread=False, timeout=10)
            cursor=connect.cursor()
            cursor.execute("SELECT * FROM friend_requests where status='pending_apply'")
            for row in cursor.fetchall():
                sender_id=row[0]
                sender_name=row[1]
                sender_ip=row[2]
                sender_timestamp=row[3]

                #登录后更新friend_request表？
                
                receiver_ip=row[6]
                print(receiver_ip)
                message={
            "type":"friendrequest",
            "sender_id":sender_id,
            "sender_name":sender_name,
            "sender_ip":sender_ip,
            "timestamp":timestamp_now
        }
                try:
                    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                        s.connect((receiver_ip, 1236))
                        s.connect((receiver_ip, 1236))
                        s.sendall(json.dumps(message).encode())
                        print(f"重发申请成功：{message['sender_name']}")
                        cursor.execute("DELETE FROM friend_requests WHERE sender_id=? and receiver_id=? and status='pending_apply'", (message["sender_id"],row[4]))
                except Exception as e:
                    print(f"重发申请失败{e}")  # 对方仍未上线
                    pass
            connect.commit()
            connect.close()
            time.sleep(30)  # 每 30 秒重试一次
def retry_agreement():
        while True:
            #print("重发同意中...")
            timestamp_now = int(time.time() * 1000)
            with sqlite3.connect("p2p.db", check_same_thread=False,timeout=10) as connect:
                cursor=connect.cursor()
                cursor.execute("SELECT * FROM friend_requests where status='pending_agreement'")
                for row in cursor.fetchall():
                    sender_id=row[0]
                    sender_name=row[1]
                    sender_ip=row[2]
                    sender_timestamp=row[3]
            with sqlite3.connect("p2p.db", check_same_thread=False,timeout=10) as connect:
                cursor=connect.cursor()
                cursor.execute("SELECT * FROM friend_requests where status='pending_agreement'")
                for row in cursor.fetchall():
                    sender_id=row[0]
                    sender_name=row[1]
                    sender_ip=row[2]
                    sender_timestamp=row[3]

                    #登录后更新friend_request表？
                    
                    receiver_ip=row[6]
                    print(receiver_ip)
                    message={
                "type":"friendrequest",
                "sender_id":sender_id,
                "sender_name":sender_name,
                "sender_ip":sender_ip,
                "timestamp":timestamp_now
                    }
                    try:
                        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
                            s.connect((receiver_ip,1236))
                            s.sendall(json.dumps(message).encode())
                            print(f"重发同意成功：{message['sender_name']}")
                            print(f"sender_id为{row(0)}")
                            cursor.execute("DELETE FROM friend_requests WHERE sender_id=? and receiver_id=? and status='pending_agreement'", (message["sender_id"],row[3]))
            
                    except Exception as e:
                        #print(f"重发同意失败{e}")  # 对方仍未上线
                        pass
                connect.commit()
                # connect.close()
                time.sleep(30)  # 每 30 秒重试一次
# def load_history(id):
#     with sqlite3.connect("p2p.db", check_same_thread=False,timeout=10) as connect:
#         cursor=connect.cursor()
#         cursor.execute("select id from current_user")
#         id_=cursor.fetchone()
#         print(f"id为{id_}")
#         id_=id_[0]
#         print(f"id为{id_}")
#         cursor.execute("select message,sent,timestamp from messages where friend_id=? and owner=?",(id,id_))
#         rows = cursor.fetchall()
#         # connect.close()
#         # 将结果转为字典列表
#         info=get_device_info()
#         history = []
#         for row in rows:
#             message=did_interface.decrypt(info["cpu_id"],info["disk_id"],info["product_id"],row[0])
#             history.append({
#                 "message": message,
#                 "sender": row[1],
#                 "timestamp": row[2]
#             })
#         return history
def load_history(id):
    print("load_history")
    try:
        with sqlite3.connect("p2p.db", check_same_thread=False, timeout=10) as connect:
            cursor = connect.cursor()
            cursor.execute("select id from current_user")
            id_ = cursor.fetchone()
            print(f"[DEBUG] 当前用户ID查询结果: {id_}")
            if not id_:
                print("[ERROR] 当前用户表为空")
                return 0

            id_ = id_[0]
            print(f"[DEBUG] 当前用户ID: {id_}")

            cursor.execute("select message,sent,timestamp from messages where friend_id=? and owner=?", (id, id_))
            rows = cursor.fetchall()
            print(f"[DEBUG] 查询到 {len(rows)} 条历史消息")

            info = get_device_info()
            history = []
            for row in rows:
                try:
                    print(f"解密前：{row[0]}")
                    message = did_interface.decrypt(info["cpu_id"], info["disk_id"], info["product_id"], row[0])
                except Exception as e:
                    print("[ERROR] 解密失败：", e)
                    message = "<解密失败>"
                    return 0
                history.append({
                    "message": message,
                    "sender": row[1],
                    "timestamp": row[2]
                })
            return history
    except Exception as e:
        print("[FATAL] load_history 出错：", e)
        return 0

def load_accept():
    with sqlite3.connect("p2p.db", check_same_thread=False, timeout=10) as connect:
        cursor = connect.cursor()
        cursor.execute("SELECT id FROM current_user")
        id_ = cursor.fetchone()[0]

        cursor.execute("""
            SELECT sender_id, sender_name 
            FROM friend_requests 
            WHERE status = 'pending_accept' AND owner = ?
        """, (id_,))

        friendlist = cursor.fetchall()
        data = {}
        for sender_id, sender_name in friendlist:
            data[sender_id] = {
                "name": sender_name,
                "status": 2  # 写死为 2
            }
        return data
def get_device_info():
        info = {
            "cpu_id": "",
            "disk_id": "",
            "product_id": ""
        }
        try:
            # 获取 CPU 序列号
            cpu_output = subprocess.check_output("wmic cpu get ProcessorId", shell=True).decode()
            info["cpu_id"] = re.findall(r"ProcessorId\s+(\w+)", cpu_output)[0].strip()

            # 获取 硬盘序列号
            # 获取硬盘序列号（修复了提取问题）
            disk_output = subprocess.check_output("wmic diskdrive get SerialNumber", shell=True).decode()
            lines = disk_output.strip().splitlines()
            serial_lines = [line.strip() for line in lines[1:] if line.strip()]
            info["disk_id"] = serial_lines[0] if serial_lines else ""
            print("Disk Output:", repr(disk_output))
            # 获取 硬盘序列号
            # 获取硬盘序列号（修复了提取问题）
            disk_output = subprocess.check_output("wmic diskdrive get SerialNumber", shell=True).decode()
            lines = disk_output.strip().splitlines()
            serial_lines = [line.strip() for line in lines[1:] if line.strip()]
            info["disk_id"] = serial_lines[0] if serial_lines else ""
            print("Disk Output:", repr(disk_output))

            # 获取 Windows 产品 ID
            product_output = subprocess.check_output("wmic os get SerialNumber", shell=True).decode()
            info["product_id"] = re.findall(r"SerialNumber\s+(.+)", product_output)[0].strip()
            # 获取 Windows 产品 ID
            product_output = subprocess.check_output("wmic os get SerialNumber", shell=True).decode()
            info["product_id"] = re.findall(r"SerialNumber\s+(.+)", product_output)[0].strip()

        except Exception as e:
            print(f"获取设备信息失败: {e}")
        return info
def delete_friend():
     pass
if __name__=='__main__':
    Agreement("did:p2p_did_chat:GRkauOstly","xxx")